<!--
* @Author: zhangjing
* @Date: 2024-01-12 10:37:36
* @Description: 学生名单
-->
<template>
	<pannel hasHeader @reback="reback">
		<div slot="header" class="header">
			<span class="class">{{ formData.className }}</span>
			<span style="margin-left: 40px">
				在线人数：
				<span class="hasBindValue">{{ bindStudentNum }}</span>
				/{{ studentList.length }}
			</span>
			<span style="margin-left: 40px" v-if="machineData.machId">
				接收器{{ machineData.machId }}：
				<span :class="[machineData.online == 1 ? 'connect' : 'no-connect']">{{
					machineData.online == 1 ? '已连接' : '未连接'
				}}</span>
			</span>
		</div>

		<template>
			<div class="list flex-1" style="padding-bottom: 50px; overflow: auto">
				<div>
					<div
						class="item flex flex-align-center"
						:class="{ checked: item.checked }"
						v-for="(item, index) in studentList"
						:key="index"
						@click="bindCard(item, index)"
					>
						<div
							class="circle"
							:class="{
								red: !machineData || machineData.online != 1 || item.status == '0',
								dot: machineData && machineData.online == 1 && item.status == '1',
							}"
						></div>
						<span class="name">{{ item.studName }}</span>
						<div class="number">答题器ID:{{ item.machineId }}</div>
						<img src="/student/unbind.png" class="icon" style="display: none" />
					</div>
				</div>
			</div>
			<div class="bind-operate flex flex-align-center">
				<a href="javascript:;" v-if="isVersion552D" class="btn bindBtn yellow mr10" @click="clear_wl"
					>全部解绑</a
				>
				<a
					href="javascript:;"
					v-if="canSwingCard && $_has('doExercise:startBind')"
					class="btn bindBtn"
					@click="toggleBind"
					:class="{
						red: isStartBind,
					}"
				>
					{{ isStartBind ? '停止绑定答题器' : '开始绑定答题器' }}
				</a>
			</div>
			<!-- 显示下一老师答题器 -->
			<div
				v-if="teacherInfo && teacherInfo.machineId && isVoiceDevice"
				class="tearcherInfo flex flex-align-center"
			>
				<div
					class="circle"
					:class="{
						red: !machineData || machineData.online != 1 || (teacherInfo && teacherInfo.status == '0'),
						dot: machineData && machineData.online == 1 && teacherInfo && teacherInfo.status == '1',
					}"
				></div>
				<span class="name">{{ teacherInfo.teacherName }}</span>
				<span style="color: #999; margin-right: 10px">(老师)</span>
				<div class="number">答题器ID:{{ teacherInfo.machineId }}</div>
			</div>
		</template>
	</pannel>
</template>

<script>
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex';
import bus from '@/utils/eventBus';
import { debounce } from '@/utils/base.js';
import pannel from './pannel.vue';
import group from './group.vue';
function compareVersions(version1, version2) {
	// 将版本号拆分成数字数组
	if (!arr1) {
		return 1;
	}
	var arr1 = version1.split('.');
	var arr2 = version2.split('.');

	// 遍历数字数组进行逐段比较
	for (var i = 0; i < Math.max(arr1.length, arr2.length); i++) {
		var num1 = parseInt(arr1[i] || 0); // 如果数组长度不够，则将缺失部分补0
		var num2 = parseInt(arr2[i] || 0);

		if (num1 < num2) {
			return -1; // 版本1小于版本2
		} else if (num1 > num2) {
			return 1; // 版本1大于版本2
		}
	}

	return 0; // 版本1等于版本2
}
export default {
	name: 'studentlist',
	components: { pannel, group },
	props: {
		//接收器信息
		machineData: {
			type: Object,
			default: () => {},
		},
		//表单数据
		formData: {
			type: Object,
			default: () => {},
		},
		// //学生数组
		// studentList: {
		// 	type: Array,
		// 	default: () => []
		// },
		consoleList: {
			type: Array,
			default: () => [],
		},
	},
	data() {
		return {
			isExpand: false, //控制台默认不展开
			testType: '',
			isStartBind: false,
			newstuList: this.studentList,
			opType: 'random',
			filename: '',
			groupList: [],
			count: 2,
		};
	},
	created() {},
	watch: {},
	computed: {
		...mapState({
			deviceType: (state) => state.websockStore.deviceType,
			studentList: (state) => state.websockStore.studentList,
			stopDeviceEventList: (state) => state.websockStore.stopDeviceEventList,
			isPro: (state) => state.isPro,
			teacherInfo: (state) => state.user.teacherInfo,
		}),
		//绑定学生人数
		bindStudentNum() {
			let list = this.studentList.filter((item) => item.status == '1');
			return this.machineData && this.machineData.online == 1 ? list.length : 0;
		},

		//是否能够刷卡绑定
		canSwingCard() {
			return (
				(this.deviceType == 'wired' ||
					(this.deviceType == 'wireless' && compareVersions(this.machineData.version, '3.0.5') > -1)) &&
				this.$_has('doExercise:startBind')
			);
		},
		//是否是552D设备，或者555p设备，需要手动解绑
		isVersion552D() {
			return this.machineData.wareVersion != 'RP552G' && this.machineData.wareVersion != 'RP554';
		},
		//是否是语音设备
		isVoiceDevice() {
			return ['RP554', 'RP555P'].includes(this.machineData.wareVersion);
		},
	},

	methods: {
		...mapMutations([
			'WEBSOCKET_SEND',
			'SET_studentList',
			'SET_STOPDEVICEEVENTLIST',
			'SET_WHITELIST',
			'SET_TEACHER_INFO',
		]),
		/* 开始绑定/停止绑定 */
		toggleBind() {
			if (!this.isStartBind) {
				let newstuList = [...this.studentList];
				let stuIds = newstuList.map((item) => item.studId);
				this.startRead(stuIds);
			} else {
				this.endRead();
			}
			//js有线接收器
			//this.$parent.send(this.isStartBind?12:13)
		},
		bindCard(item, index) {
			console.log(JSON.stringify(item));
			if (!this.isStartBind) {
				return;
			}
			if (item.machineId) {
				return;
			}
			let newstuList = [...this.studentList];
			newstuList[index].checked = !newstuList[index].checked;
			this.SET_studentList(newstuList);
		},
		//开始读卡
		startRead(stuIds) {
			//左侧菜单需要用的数据
			let leftOperateData = this.$ls.get('leftOperateData');
			if (this.deviceType == 'wired') {
				if (!this.isStartBind) {
					this.isStartBind = true;
					this.WEBSOCKET_SEND({ fun: 'read_card_start' });
					if (this.machineData.wareVersion != 'RP552G' && this.machineData.wareVersion != 'RP554') {
						if (!this.stopDeviceEventList.includes('read_card_stop')) {
							let eventlist = this.stopDeviceEventList || [];
							eventlist.push('read_card_stop');
							this.SET_STOPDEVICEEVENTLIST(eventlist);
						}
					}
				}
			} else {
				let parameter = {
					classId: this.formData.classId,
					stuIds: stuIds && stuIds.length > 0 ? stuIds : this.newstuList.map((item) => item.studId),
				};
				/* return this.$postAction(this.$sysManageapi.answerUrl.startRead + '?machid=' + this.machineData.machId).then(res => { */
				return this.$postAction(this.$sysManageapi.answerUrl.startRead, parameter).then((res) => {
					if (res && res.code == 1) {
						this.isStartBind = true;
					} else {
						this.isStartBind = false;
					}
					this.setLeftOperateData(leftOperateData.curMenu, this.isStartBind);
				});
			}
		},
		//停止读卡
		endRead() {
			let leftOperateData = this.$ls.get('leftOperateData');
			if (this.deviceType == 'wired') {
				this.WEBSOCKET_SEND({ fun: 'read_card_stop' });
				let newstuList = [...this.studentList];
				newstuList.forEach((item) => {
					item.checked = false;
				});
				this.SET_studentList(newstuList);
				this.isStartBind = false;
				this.setLeftOperateData(leftOperateData.curMenu, this.isStartBind);
				if (
					this.machineData.wareVersion != 'RP552G' &&
					this.machineData.wareVersion != 'RP554' &&
					this.stopDeviceEventList.includes('read_card_stop')
				) {
					let stopDeviceEventList = [...this.stopDeviceEventList];
					stopDeviceEventList = stopDeviceEventList.filter((item) => item != 'read_card_stop');
					this.SET_STOPDEVICEEVENTLIST(stopDeviceEventList);
				}
			}
		},

		//返回
		reback() {
			this.$emit('checkMenu', { type: 'studentlist' });
		},
		//清空白名单
		clear_wl() {
			if (this.formData.classId) {
				this.$postAction(this.$sysManageapi.uploadWiredUrl.clearWl + '?classId=' + this.formData.classId);
				var message = {
					fun: 'clear_wl',
					uID: 0,
				};
				let teacherInfo = { ...this.teacherInfo };
				teacherInfo.status = '0';
				console.log('teacherInfo', teacherInfo);
				this.SET_TEACHER_INFO(teacherInfo);
				this.WEBSOCKET_SEND(message);
				let newstuList = [...this.studentList];
				newstuList.forEach((item) => {
					item.status = '0';
				});
				this.SET_studentList(newstuList);
				this.SET_WHITELIST([]); //清空白名单
			}
		},
		beforeUpload(file) {
			this.importFile(file);
			return false;
		},
		normFile(e) {
			if (Array.isArray(e)) {
				return e;
			}
			this.filename = e.file.name;
			return e && e.file;
		},
		importFile(file) {
			// this.confirmLoading = true;
			const formData = new FormData();

			formData.append('file', file);
			formData.append('classId', this.formData.classId);
			formData.append('subjectCode', this.formData.subjectCode);

			postActionUpload(sysManageapi.answerUrl.uploadGroup, formData)
				.then((res) => {
					if (res.code == 1) {
						// this.confirmLoading = false;
						this.$message.success('导入成功');
						this.filename = '';
						this.getGroupList();
					}
				})
				.finally(() => {
					// this.confirmLoading = false;
				});
		},
		downGroupTempl() {
			this.$postActionExport(
				this.$sysManageapi.answerUrl.downGroupTempl + '?classId=' + this.formData.classId
			).then((res) => {
				let BlobFile = res;
				let fileName = 'group.xlsx';
				console.log(BlobFile);
				let blobObject = new Blob([BlobFile], {
					//type: 'application/vnd.ms-excel,charset=utf-8',
					type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
				}); //如果是字节流
				//是IE浏览器
				if (!!window.ActiveXObject || 'ActiveXObject' in window) {
					window.navigator.msSaveOrOpenBlob(blobObject, fileName);
				} else {
					//火狐谷歌都兼容
					//模板中要有一个预定义好的a标签
					var link = document.createElement('a');
					link.href = window.URL.createObjectURL(blobObject); //如果是字节流
					//link.href = BlobFile;
					link.target = '_blank';
					link.download = fileName;
					link.click();
					//释放内存
					window.URL.revokeObjectURL(link.href);
				}
				this.$message.success('导出成功');
			});
		},
	},
};
</script>

<style lang="less" scoped>
.header {
	font-size: 22px;
	color: #fff;
	text-align: center;
	width: 100%;
	.class {
		letter-spacing: -1px;
	}

	.sign {
		margin: 0 40px;
	}

	.hasBindValue {
		color: @warning-color;
	}

	.no-connect {
		color: @warning-color;
	}

	.connect {
		color: #fff;
	}
}
.list {
	padding: 20px 62px 40px;
	.item {
		width: 50%;
		display: inline-block;
		cursor: pointer;
		text-align: left;
		margin-bottom: 30px;

		&:nth-child(even) {
			text-align: right;
		}

		.name {
			//margin-right: 18px;
			width: 5em;
			display: inline-block;
			text-align: left;
			word-break: break-all;
			vertical-align: middle;
			margin-right: 10px;
		}

		.circle {
			width: 20px;
			height: 20px;
			border-radius: 100%;
			// background: rgb(255, 255, 255);
			background: @primary-color;
			border: 2px solid @primary-color;
			margin-right: 18px;
			display: inline-block;
			vertical-align: middle;
			position: relative;
			//margin-top: -5px;

			&.red {
				border: 2px solid rgb(230, 67, 67);
				background: rgb(230, 67, 67);
				cursor: pointer;
			}
			&.dot {
				background: @primary-color;
			}
		}

		.icon {
			width: 24px;
			height: 24px;
			margin-left: 18px;
		}

		.number {
			display: inline-block;
			width: 12em;
			text-align: left;
			vertical-align: middle;
		}

		&.checked {
			.circle {
				&.red {
					position: relative;

					&::after {
						position: absolute;
						top: 40%;
						left: 50%;
						transform: translate(-50%, -50%) rotate(-45deg);
						content: '';
						width: 12px;
						height: 8px;
						border: 2px solid transparent;
						border-left-color: #fff;
						border-bottom-color: #fff;
					}
				}
			}
		}
	}
}
.tearcherInfo {
	position: absolute;
	bottom: 40px;
	left: 80px;
	z-index: 1;
	font-size: 20px;
	color: #2e2424;
	.name {
		//margin-right: 18px;
		display: inline-block;
		text-align: left;
		word-break: break-all;
		vertical-align: middle;
		margin-right: 10px;
	}

	.circle {
		width: 20px;
		height: 20px;
		border-radius: 100%;
		// background: rgb(255, 255, 255);
		background: @primary-color;
		border: 2px solid @primary-color;
		margin-right: 18px;
		display: inline-block;
		vertical-align: middle;
		position: relative;
		//margin-top: -5px;

		&.red {
			border: 2px solid rgb(230, 67, 67);
			background: rgb(230, 67, 67);
			cursor: pointer;
		}
		&.dot {
			background: @primary-color;
		}
	}

	.icon {
		width: 24px;
		height: 24px;
		margin-left: 18px;
	}

	.number {
		display: inline-block;
		width: 12em;
		text-align: left;
		vertical-align: middle;
	}
}

/deep/.bind-operate {
	//height: 50px;
	position: absolute;
	bottom: 40px;
	right: 80px;
	z-index: 1;
	text-align: right;
	.backBtn {
		border-radius: 23px;
		width: 80px;
		height: 34px;
		font-size: 16px;
		margin-left: 10px;
	}
}
/deep/.bindBtn {
	&.btn {
		display: block;
		min-width: 120px;
		padding: 0 20px !important;
		text-align: center;
		border-radius: 23px;
		background: @primary-color;
		height: 34px;
		line-height: 34px;
		font-size: 16px;
		color: #fff;
		cursor: pointer;
		span {
			letter-spacing: 2px !important;
			margin-right: -2px !important;
		}

		&.blue {
			background: #5480db;

			&:focus,
			&:active {
				//background: rgba(84,128,219,0.5);
				//border-color: rgba(84, 128, 219, 0.5);
			}
		}

		&.yellow {
			background: #fc9700;

			&:focus,
			&:active {
				//background: rgba(252,151,0,0.5);
				border-color: rgba(252, 151, 0, 0.5);
			}
		}
		&.red {
			background: #e64343;
			border-color: rgba(230, 67, 67, 0.5);
		}
	}
}

</style>
